package com.mamesoft.medicipazienti.servlet;

import com.itextpdf.text.BadElementException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.mamesoft.medicipazienti.tools.JDBC;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.ResultSet;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class PreparaLettereServlet extends HttpServlet {

    private static Logger log = Logger.getLogger(PreparaLettereServlet.class);

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PropertyConfigurator.configure(PreparaLettereServlet.class.getClassLoader().getResource("com/mamesoft/medicipazienti/tools/log4j.properties"));

        Connection connect = null;
        PrintWriter out = null;
        try {
            HttpSession session = request.getSession();
            connect = JDBC.connect();
            DateFormat c = DateFormat.getDateTimeInstance();
            String nome = (String) session.getAttribute("nome");
            String cognome = (String) session.getAttribute("cognome");

            Boolean isOk = false;


            ArrayList<Integer> ID = (ArrayList) session.getAttribute("ID");
            String path = null;
            ArrayList<Paziente> pazienti = new ArrayList();
            Timestamp t = null;
            if (ID != null) {
                isOk = true;
                for (int i = 0; i < ID.size(); i++) {
                    pazienti.add(new Paziente(ID.get(i), connect));
                }

                t = new Timestamp((Long) session.getAttribute("time"));
                ResultSet set;

                set = JDBC.executeQuery("SELECT ID FROM medico WHERE nome='" + nome + "' AND cognome = '" + cognome + "'", connect);
                set.next();
                int mID = set.getInt("ID");
                for (int i = 0; i < pazienti.size(); i++) {
                    String stat = "INSERT INTO `vaccino` (`mID`, `data`, `pID`) "
                            + "VALUES ('" + mID + "','" + t.toString() + "', '" + pazienti.get(i).pID + "');";
                    JDBC.executeStatement(stat, connect);
                }
                set.close();

                path = toPDF(c.format(t), pazienti, nome + " " + cognome);
            }
            session.removeAttribute("ID");
            response.setContentType("text/html;charset=UTF-8");
            
            out = response.getWriter();

            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("    <head>");
            out.println("        <title>Vaccino Manger</title>");
            out.println("        <link rel=\"stylesheet\" type=\"text/css\" href=\"/MediciPazienti/variant-stream.css\" title=\"Variant Stream\" media=\"screen,projection\" />");
            out.println("        <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">       ");
            out.println("    </head>");

            out.println("    <body>");
            out.println("        <div id =\"wrap\">");
            out.println("            <div id=\"header\">");
            out.println("                <div id =\"topmenu\">");
            out.println("                    <p>");
            out.println("                        <a href=\"/MediciPazienti/logout\">Logout</a>");
            out.println("                    </p>");
            out.println("                </div>");
            out.println("                <div id=\"title\">");
            out.println("                    <h1>Vaccino Manager</h1><br/>");
            out.println("                    <h2 class =\"slogan\">I tuoi vaccini contano</h2>");
            out.println("                </div>");
            out.println("            </div>");

            out.println("            <div id=\"sidebar\">");
            out.println("               <ul class = \"sidemenu\">");
            out.println("                   <li><a href=\"/MediciPazienti/medico/welcome\">Home</a><li>");
            out.println("                   <li><a class=\"active\" href=\"/MediciPazienti/medico/richiama\">Invia richiami</a><li>");
            out.println("                   <li><a href=\"/MediciPazienti/medico/visualizza_storico\">Visualizza Storico</a><li>");
            out.println("                   <li><a href=\"/MediciPazienti/logout\">Logout</a><li>");
            out.println("               </ul>");
            out.println("            </div>");

            out.println("            <div id =\"content\">");
            out.println("                <div id=\"feature\">");
            out.println("                    <p>" + session.getAttribute("last_login") + "</p>");
            out.println("</p>");
            out.println("                </div>");
            out.println("                <div class=\"post\">");

            if (isOk) {
                out.println("<h2>Inviati inviti per richiami con successo</h2>");
                out.println(pazienti.get(0).paziente);
                for (int i = 1; i < pazienti.size(); i++) {
                    out.println(", " + pazienti.get(i).paziente);
                }
                out.println(" sarà/anno vacinato/i!<br><br><br>");
                out.println("<a href=\"" + path + "\">" + path + "</a><br/><br/>");
                session.setAttribute("PDFPath", path);

                out.println("<a href =\"/MediciPazienti/medico/welcome\"> Torna alla pagina di Benvenuto!</a> ");
            } else {
                out.println("<p>Non è stato selezionato nessun paziente, tornare "
                        + "indietro e rieffettuare la selezione</>");
                out.println("<a href =\"/MediciPazienti/medico/richiama\"> Torna Indietro</a> ");
            }


            out.println("                </div>");
            out.println("            </div>");
            out.println("            <div id=\"footer\">");
            out.println("                <p class=\"centered\">Copyright &copy; 2011 <a href=\"/MediciPazienti/index.html\">Mamesoft</a>");
            out.println("                    Progetto Programmazione per il web A.A.2011/2012</p>");
            out.println("            </div>");
            out.println("        </div>");
            out.println("    </body>");
            out.println("</html>");

        } catch (Exception ex) {
            request.getSession().invalidate();
            if (ex instanceof SQLException | (ex instanceof ClassNotFoundException & ex instanceof InstantiationException & ex instanceof IllegalAccessException)) {
                log.error("Database Error: " + ex.toString());
                response.sendRedirect("/MediciPazienti/database_error.html");
            } else {
                if (ex instanceof DocumentException | ex instanceof FileNotFoundException | ex instanceof BadElementException
                        | ex instanceof MalformedURLException | ex instanceof IOException) {
                    log.error("Document Error:" + ex.toString());
                    response.sendRedirect("/MediciPazienti/document_error.html");
                } else {
                    log.error("Generic error: " + ex.toString());
                    response.sendRedirect("/MediciPazienti/general_error.html");
                }
            }
        } finally {            
            if (out != null) {
                out.close();
            }
            if (connect != null) {
                try {
                    connect.close();
                } catch (Exception ex) {
                    request.getSession().invalidate();
                    log.error("Database Error: " + ex.toString());
                    response.sendRedirect("/MediciPazienti/database_error.html");
                }
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    String toPDF(String dataRichiamo, ArrayList<Paziente> pazienti, String medico)
            throws DocumentException, FileNotFoundException, BadElementException,
            MalformedURLException, IOException {

        Document document = new Document();

        String[] token = dataRichiamo.split(" ");

        String data = token[0];
        String ora = token[1];
        String file = medico + "_" + data + "_" + ora;
        file = file.replace(" ", "-");
        file = file.replace("/", "_");
        file = file.replace(".", "-");
        file += ".pdf";

        PdfWriter.getInstance(document, new FileOutputStream(getServletContext().getRealPath("/") + "PDF/" + file));

        document.open();

        for (int j = 0; j < pazienti.size(); j++) {
            document.newPage();

            Paragraph header = new Paragraph();
            Image logo = new Image(Image.getInstance(getServletContext().getRealPath("/") + "images/head.jpg")) {
            };
            logo.scalePercent(52);
            header.add(logo);
            header.add("\n\n\n\n");
            document.add(header);

            Paragraph p1 = new Paragraph("Spettabile " + pazienti.get(j).paziente + ",\n", FontFactory.getFont(FontFactory.HELVETICA, 10));
            p1.add("\nLa informiamo dovrà sottoporsi a vaccino in data " + data + " alle ore " + ora);

            p1.add("\n\n");
            document.add(p1);

            Paragraph p2 = new Paragraph("", FontFactory.getFont(FontFactory.HELVETICA, 10));
            p2.setAlignment(Paragraph.ALIGN_BOTTOM);


            if (!pazienti.get(j).data.isEmpty()) {
                p2.add("\nUltimi vaccini effettuati: \n");
                PdfPTable table = new PdfPTable(2);
                Phrase p = new Phrase("Data", FontFactory.getFont(FontFactory.HELVETICA_BOLD, 10));
                PdfPCell cell = new PdfPCell(p);
                cell.setBorderWidth(1);
                table.addCell(cell);
                p = new Phrase("Medico", FontFactory.getFont(FontFactory.HELVETICA_BOLD, 10));
                cell.setBorderWidth(1);
                cell.setPhrase(p);
                table.addCell(cell);

                for (int i = 0; i < pazienti.get(j).data.size(); i++) {
                    p = new Phrase(pazienti.get(j).data.get(i), FontFactory.getFont(FontFactory.HELVETICA, 10));
                    cell = new PdfPCell(p);
                    table.addCell(cell);
                    p = new Phrase("Dr. " + pazienti.get(j).medico.get(i), FontFactory.getFont(FontFactory.HELVETICA, 10));
                    cell.setPhrase(p);
                    table.addCell(cell);
                }
                p2.add(table);
            } else {
                p2.add("\nRisulta che Lei non sia mai stato vaccinato prima \n");
            }

            p2.add("\n\n\n\n\n\n\n\n\n\nIl Suo medico di fiducia");
            document.add(p2);
        }
        document.close();
        return getServletContext().getContextPath() + "/PDF/" + file;
    }

    private class Paziente {

        String paziente;
        int pID;
        ArrayList<String> data, medico;
        String query;

        Paziente(int ID, Connection connect) throws SQLException {
            DateFormat c = DateFormat.getDateTimeInstance();
            data = new ArrayList<String>();
            medico = new ArrayList<String>();
            query = "SELECT paziente.ID AS pID, paziente.nome AS Nome, paziente.cognome AS Cognome, "
                    + "vaccino.data AS Data, medico.nome AS NomeMedico, "
                    + "medico.cognome AS CognomeMedico "
                    + "FROM paziente LEFT JOIN vaccino ON (paziente.ID = pID) "
                    + "LEFT JOIN medico ON (medico.id = mID) "
                    + "WHERE paziente.ID = '" + ID + "' ";
            ResultSet set = JDBC.executeQuery(query, connect);
            set.next();
            pID = set.getInt("pID");
            paziente = set.getString("Nome") + " " + set.getString("Cognome");
            do {
                if (set.getTimestamp("Data") != null) {
                    data.add(c.format(set.getTimestamp("Data")));
                }
                if (set.getString("CognomeMedico") != null) {
                    medico.add(set.getString("NomeMedico") + " " + set.getString("CognomeMedico"));
                }
            } while (set.next());
            set.close();
        }
    }
}
